package com.sneakxy.cloudbase.platform.service;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.CredentialsMatcher;
import org.springframework.security.crypto.password.PasswordEncoder;

import com.sneakxy.cloudbase.platform.shiro.UsernameCodeToken;

/**
 * 认证校验密码
 * @author 潜行的青衣
 * @see
 */
public class PasswordCredentialsMatcher implements CredentialsMatcher {

	private PasswordEncoder passwordEncoder;
	
	public PasswordCredentialsMatcher() {}
	
	public PasswordCredentialsMatcher(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}
	
	/* (non-Javadoc)
	 * @see org.apache.shiro.authc.credential.CredentialsMatcher#doCredentialsMatch(org.apache.shiro.authc.AuthenticationToken, org.apache.shiro.authc.AuthenticationInfo)
	 */
	@Override
	public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
		if(info instanceof UsernameCodeToken) {
			return StringUtils.equals(new String((char[]) token.getCredentials()), ((UsernameCodeToken) token).getCode());
		}
		return this.passwordEncoder.matches(new String((char[]) token.getCredentials()), (String) info.getCredentials());
	}

	public PasswordEncoder getPasswordEncoder() {
		return passwordEncoder;
	}

	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

}
